<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebGL</title>
</head>

<body>
    <canvas width="300" height="300"></canvas>
    <script>
        //创建 WebGL 上下文
        const canvas = document.querySelector('canvas');
        const gl = canvas.getContext('webgl');
        //创建两个着色器
        //将数据通过 varying 变量传给片元着色器
        const vertex = `
      attribute vec2 position;
      varying vec3 color;
      void main() {
        gl_PointSize = 1.0;
        color = vec3(0.5 + position * 0.5, 0.0);
        gl_Position = vec4(position * 0.5, 1.0, 1.0);
      }
    `;
        //将 color 通过 varying 变量传给片元着色器
        const fragment = `
      precision mediump float;
      varying vec3 color;
      void main()
      {
        gl_FragColor = vec4(color, 1.0);
      }    
    `;
        //将着色器创建为对象，为编写程序做准备
        const vertexShader = gl.createShader(gl.VERTEX_SHADER);
        gl.shaderSource(vertexShader, vertex);
        gl.compileShader(vertexShader);

        const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
        gl.shaderSource(fragmentShader, fragment);
        gl.compileShader(fragmentShader);

        //创建 WebGLProgram 对象，并将这两个 shader 关联到这个 WebGL 程序上
        const program = gl.createProgram();
        gl.attachShader(program, vertexShader);
        gl.attachShader(program, fragmentShader);
        gl.linkProgram(program);
        //通过 useProgram 选择启用这个 WebGLProgram 对象
        gl.useProgram(program);
        //定义这个三角形的三个顶点
        const points = new Float32Array([
            -1, -1,
            0, 1,
            1, -1,
        ]);
        //将定义好的数据写入 WebGL 的缓冲区
        const bufferId = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, bufferId);
        gl.bufferData(gl.ARRAY_BUFFER, points, gl.STATIC_DRAW);
        //将 buffer 的数据绑定给顶点着色器的 position 变量
        const vPosition = gl.getAttribLocation(program, 'position');
        gl.vertexAttribPointer(vPosition, 2, gl.FLOAT, false, 0, 0);
        gl.enableVertexAttribArray(vPosition);
        //执行着色器程序完成绘制
        gl.clear(gl.COLOR_BUFFER_BIT);
        gl.drawArrays(gl.TRIANGLES, 0, points.length / 2);
    </script>
</body>

</html>